package com.caolei1992.api.config;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author caolei
 * @version 1.0
 * @since 2019/2/15
 * 公共字段自动自动填充，建议所有的实体都添加创建时间与修改时间
 */
@Component
public class MetaObjectHandlerConfig implements MetaObjectHandler {
    /**
     * 对应是实体中的字段
     */
    private static final String CREATE_TIME = "createTime";
    private static final String UPDATE_TIME = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        Object createTime = getFieldValByName(CREATE_TIME, metaObject);
        Object updateTime = getFieldValByName(UPDATE_TIME, metaObject);
        Date date = DateUtil.date();
        if (createTime == null) {
            setFieldValByName(CREATE_TIME, date, metaObject);
        }
        if (updateTime == null) {
            setFieldValByName(UPDATE_TIME, date, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Date date = DateUtil.date();
        setFieldValByName(UPDATE_TIME, date, metaObject);
    }
}
